#include <iostream>
#include <vector>
#include <memory>

using namespace std;



/**
 * 假设设计一个二叉树，并在其中包含一个指向左右子节点的指针
 * 运行正常，调用3次构造函数和3次析构函数，输出如下：
 * Constructor
 * Constructor
 * Constructor
 * 1
 * 1
 * 1
 * Destructor
 * Destructor
 * Destructor
 */
class Node {
    int value;
public:
    shared_ptr<Node> leftPtr;
    shared_ptr<Node> rightPtr;
    //如果给每个节点添加一个父节点时，则导致share_ptr内测泄漏。
//    shared_ptr<Node> parentPtr;
    //使用弱引用进行处理，交叉引用不递增计数器
    weak_ptr<Node> parentPtr;

    Node(int val) : value(val) {
        cout << "Constructor" << endl;
    }
    ~Node() {
        cout << "Destructor" << endl;
    }
};

void test1()
{
    shared_ptr<Node> ptr = make_shared<Node>(4);
    ptr->leftPtr = make_shared<Node>(2);
    ptr->rightPtr = make_shared<Node>(5);
    cout<<ptr.use_count()<<endl;
    cout<<ptr->leftPtr.use_count()<<endl;
    cout<<ptr->rightPtr.use_count()<<endl;
}

void test2()
{
    shared_ptr<Node> ptr = make_shared<Node>(4);
    cout<< "shared_ptr<Node> ptr = make_shared<Node>(4):  " << ptr.use_count()<<endl;
    ptr->leftPtr = std::make_shared<Node>(2);
    cout<< "ptr->leftPtr = std::make_shared<Node>(2):  " << ptr.use_count()<<endl;
    ptr->leftPtr->parentPtr = ptr;
    cout<< " ptr->leftPtr->parentPtr = ptr:  " << ptr.use_count()<<endl;
    ptr->rightPtr = std::make_shared<Node>(5);
    cout<< " ptr->rightPtr = std::make_shared<Node>(5):  " << ptr.use_count()<<endl;
    ptr->rightPtr->parentPtr = ptr;
    cout<< "ptr->rightPtr->parentPtr = ptr:  " << ptr.use_count()<<endl;

    cout<< "leftPtr.use_count():  " << ptr->leftPtr.use_count()<<endl;
    cout<< "ptr->rightPtr.use_count():  " << ptr->rightPtr.use_count()<<endl;
}


int main(){
//    test1();
    test2();
    return 0;
}
